import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { message } from 'ant-design-vue'
import router from '@/router'
import { get_user_info, logout_api } from '@/api/login'
import type { UserInfo } from '@/types/user'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const userInfo = ref<UserInfo | null>(null)

    const isLogin = computed(() => !!token.value)

    async function _loadUser() {
      if (!token.value) return
      try {
        const { data } = await get_user_info()
        userInfo.value = data as UserInfo
      } catch (e) {
        message.error('获取用户信息失败')
        await logout()
      }
    }

    async function login(newToken: string) {
      token.value = newToken
      await _loadUser()
    }

    async function logout() {
      try { await logout_api() } catch {}
      token.value = ''
      userInfo.value = null
      router.replace('/')
    }

    async function fetchLoginUser() {
      await _loadUser()
    }

    function setLoginUser(info: UserInfo) {
      userInfo.value = info
    }

    return {
      token,
      userInfo,
      isLogin,
      login,
      logout,
      fetchLoginUser,
      setLoginUser,
    }
  },
  {
    persist: {
      key: 'user',
      paths: ['token', 'userInfo'],
    },
  },
)
